<template>
	<view class="unique-result-wrap">
		<image class="header-img" src="/static/images/1_r1_c1.jpg"></image>
		<text class="tips" v-if="unicodeInfo.serialNo">恭喜你，该产品为京润珍珠正品</text>
		<view v-if="isEmpty" class="empty-box">
			<image class="empty-img" src="/static/images/empty.png"></image>
			<text class="empty-text">无效唯一码</text>
		</view>
		<view v-else>
			<view class="content">
				<view class="content-cell">
					<view class="content-cell-label space-10">唯一码</view>
					<view class="content-cell-label">：</view>
					<view class="content-cell-control">{{maskCode(unicodeInfo.serialNo)}}</view>
				</view>
				<view class="content-cell">
					<view class="content-cell-label">产品名称：</view>
					<view class="content-cell-control">{{unicodeInfo.goodsName}}</view>
				</view>
				<view class="content-cell">
					<view class="content-cell-label">货品编码：</view>
					<view class="content-cell-control">{{unicodeInfo.goodsNo}}</view>
				</view>
				<!-- <view class="content-cell">
					<view class="content-cell-label">购买时间：</view>
					<view class="content-cell-control">{{unicodeInfo.tradeTime}}</view>
				</view> -->
			</view>
			<button v-if="unicodeInfo.hideBtn === 0" :disabled="unicodeInfo.isGet" class="get-btn" v-on:click="handleWarrantyCertificate(serialId)">
				{{unicodeInfo.isGet === 1 ? '该电子质保单已被领取' : unicodeInfo.isGet === 2 ? '该订单已退款' : '点击领取电子质保单'}}
			</button>
		</view>
		
		<button class="search-btn" v-on:click="gotoWarrantySearch">搜索其他订单</button>
		
		<view class="rich-ad" v-if="is_show">
			<rich-text :nodes="adNode"></rich-text>
		</view>
		
		<image class="footer-img" src="/static/images/1_r7_c2.jpg"></image>
		
		<view v-if="showErrorMsgModal" class="error-modal">
			<view class="error-modal-content">
				<view>{{errorMsg.alertMsg}}</view>
				<image :src="errorMsg.customerImg" class="error-modal-img" :show-menu-by-longpress="true"></image>
				<view class="error-modal-close" @click="showErrorMsgModal = false">关闭</view>
			</view>
		</view>
		
		<view class="customer-icon" @tap="goGoodCall">
			<text class="iconfont icon-ic_customerservice fs-40"></text>
			<text class="fs-18">客服</text>
		</view>
		<view class="goback-icon" @tap="goTop">
			<text class="iconfont icon-ic_up2 fs-40"></text>
			<text class="fs-18">置顶</text>
		</view>
		<pageFooter :style="colorStyle"></pageFooter>
	</view>
</template>

<script>
	import { mapGetters } from "vuex";
	import pageFooter from '@/components/pageFooter/index.vue';
	import { toLogin } from '@/libs/login.js';
	import { getOrderByQrcode, getAdDetail } from '@/api/unicode.js';
	import { getWarrantyCertificate } from '@/api/warranty.js';
	export default {
		name: "UniqueCodeResult",
		data() {
			return {
				unicodeInfo: {},
				serialId: undefined,
				isEmpty: false,
				adNode: "",
				is_show: 0,
				showErrorMsgModal: false,
				errorMsg: {
					alertMsg: '',
					customerImg: ''
				}
			};
		},
		components: {
		  pageFooter
		},
		computed: {
		  ...mapGetters({
		    isLogin: 'isLogin'
		  })
		},
		mounted() {
			this.getNode();
		},
		onLoad(options) {
			const query = decodeURIComponent(options.q);
			const obj = this.getFormattedSearchParams(query); // 直接微信扫一扫扫过来的
			
			const serialId = options?.serialId || obj?.serialId;
			
			if(serialId) {
				this.serialId = serialId;
			}
		},
		onShow() {
			if(this.isLogin === false) {
				toLogin();
			} else if(this.serialId && !this.unicodeInfo.serialId) {
				this.init(this.serialId);
			}
			// if(this.serialId && !this.unicodeInfo.serialId) {
			// 	this.init(this.serialId);
			// }
		},
		methods: {
			goTop() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 0
				});
			},
			goGoodCall() {
				let userInfo = uni.getStorage("USER_INFO")
				// let url = `/pages/extension/customer_list/chat?productId=${this.id}`
				// let obj = {
				// 	store_name: this.storeInfo.store_name,
				// 	path: `/pages/goods_details/index?id=${this.storeInfo.id}`,
				// 	image:this.storeInfo.image
				// }
				this.$util.getCustomer(userInfo, null, null, 0)
			},
			getNode() {
				getAdDetail({id: 2}).then((res) => {
					if(res?.status === 200 && res?.data) {
						this.adNode = res?.data?.content;
						this.is_show = res?.data?.is_show;
					}
				}).catch((msg) => {
					this.is_show = 0;
				});
			},
			gotoWarrantySearch() {
				uni.switchTab({
					url: '/pages/warranty/search'
				})
			},
			maskCode(code) {
			    return code?.replace(/^(.{4})(.*)(.{4})$/, function(match, p1, p2, p3) {
			        return p1 + '*'.repeat(p2.length) + p3;
			    });
			},
			init(serialId) {
				getOrderByQrcode({serialNo: serialId}).then((res) => {
					if(res?.status === 200 && res?.data) {
						if(res?.data?.[0]?.justShowResult === 1) {
							this.errorMsg = res?.data[0];
						}
						
						this.unicodeInfo = res?.data[0];
					} else {
						this.isEmpty = true;
						uni.showToast({
							icon: 'error',
							title: "唯一码无效！"
						})
					}
				}).catch((msg) => {
					this.isEmpty = true;
					
					uni.showToast({
						icon: 'error',
						title: msg && typeof msg === "string" ? msg : "唯一码无效！"
					})
				});
			},
			handleWarrantyCertificate(serialId) {
				if(this.isLogin === false) {
					toLogin();
				} else if(this.unicodeInfo.justShowResult === 1) {
					this.showErrorMsgModal = true;
				} else {
					getWarrantyCertificate({serialNo: serialId}).then((res) => {
						if(res?.status == 200) {
							uni.showToast({
								title: "领取成功！"
							}).then(() => {
								uni.navigateTo({
									url:"/pages/warranty/result?serialId=" + serialId
								})
							})
						} else {
							uni.showToast({
								icon: 'error',
								title: "领取失败！"
							})
						}
					}).catch((msg) => {
						uni.showToast({
							icon: 'error',
							title: msg && typeof msg === "string" ? msg : "领取失败！"
						})
					});
				}
				
			},
			getFormattedSearchParams(url) {
			  // 提取查询字符串部分
			  const queryString = url.split('?')[1];
			
			  // 如果没有查询字符串，返回空对象
			  if (!queryString) {
			    return {};
			  }
			
			  // 分割成键值对数组
			  const pairs = queryString.split('&');
			
			  // 创建一个空对象用于存储格式化后的参数
			  const params = {};
			
			  // 遍历每个键值对
			  for (const pair of pairs) {
			    // 跳过空字符串（处理连续的 & 符号）
			    if (!pair) continue;
			
			    // 分割成键和值，并解码
			    const [key, value] = pair.split('=').map(decodeURIComponent);
			
			    // 如果参数中已有该键，且该键的值不是数组，则将其转换为数组
			    if (params[key]) {
			      if (!Array.isArray(params[key])) {
			        params[key] = [params[key]];
			      }
			      params[key].push(value);
			    } else {
			      params[key] = value;
			    }
			  }
			
			  return params;
			}
		}
	};
</script>

<style scoped lang="scss">
	page {
		background-color: #86151a !important;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		
		.error-modal {
			position: fixed;
			top: 0;
			left: 0;
			background-color: rgba(0, 0, 0, 0.6);
			height: 100vh;
			width: 100vw;
		}
		
		.error-modal-content {
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate3d(-50%, -60%, 0);
			padding: 40rpx;
			width: 600rpx;
			text-align: center;
			background-color: #fff;
		}
		
		.error-modal-img {
			margin-top: 40rpx;
			width: 480rpx;
			height: 480rpx;
		}
		
		.error-modal-close {
			font-size: 38rpx;
			position: absolute;
			bottom: -40px;
			left: 50%;
			color: #fff;
			transform: translateX(-50%);
		}
		
		.rich-ad {
			margin: 40rpx;
		}
		
		.empty-box {
			height: 568rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
		}
		
		.empty-img {
			height: 240rpx;
			width: 360rpx;
		}
		
		.empty-text {
			font-size: 32rpx;
			margin-top: 18rpx;
			margin-bottom: 32rpx;
		}
		
		.unique-result-wrap {
			min-height: 100vh;
			background: url("@/static/images/1_r3_c1.jpg");
			background-size: contain;
			padding-bottom: 156rpx;
			border-bottom: 16rpx solid #86151a;
		}
		
		.header-img {
			height: 168rpx;
			width: 750rpx;
		}
		
		.space-10 {
			letter-spacing: 10rpx;
		}
		
		.content {
			padding: 0 60rpx;
			
			&-cell {
				display: flex;
				align-items: center;
				line-height: 84rpx;
				border-bottom: 1rpx dashed #ddd;
				
				&-label {
					color: #666;
					font-weight: 200;
				}
				
				&-control {
					color: #86151a;
				}
			}
		}
		
		.tips {
			color: #86151a;
			display: block;
			font-size: 36rpx;
			font-weight: 200;
			text-align: center;
			margin: 20rpx auto 40rpx;
		}
		
		.get-btn {
			font-size: 14px;
			border-radius: 4rpx;
			margin: 60rpx auto 0;
			width: 340rpx;
			padding: 8rpx 0;
			color: #fff;
			background-color: #86151a;
			border: 2rpx solid #86151a;
			
			&[disabled] {
				border: 2rpx solid #adacac;
				background-color: #adacac;
			}
		}
		
		.search-btn {
			font-size: 14px;
			border-radius: 4rpx;
			margin: 0 auto;
			width: 340rpx;
			padding: 8rpx 0;
			color: #86151a;
			border: 2rpx solid #86151a;
			background-color: transparent;
			margin-top: 40rpx;
		}
		
		.footer-img {
			display: block;
			height: 564rpx;
			width: 650rpx;
			margin: 80rpx auto 0;
		}
	}
	.customer-icon {
		position: fixed;
		bottom: 280rpx;
		right: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		background-color: #fff;
		box-shadow: 0 0 6rpx #750c1082;
		width: 100rpx;
		height: 100rpx;
		color: #fff;
		background-color: #750c1082;
		border-radius: 50%;
		margin-bottom: constant( safe-area-inset-bottom); /* 兼容 iOS < 11.2 */
		margin-bottom: env( safe-area-inset-bottom); /* 兼容 iOS >= 11.2 */
	}
	.goback-icon {
		position: fixed;
		bottom: 160rpx;
		right: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		background-color: #fff;
		box-shadow: 0 0 6rpx #750c1082;
		width: 100rpx;
		height: 100rpx;
		color: #fff;
		background-color: #750c1082;
		border-radius: 50%;
		margin-bottom: constant( safe-area-inset-bottom); /* 兼容 iOS < 11.2 */
		margin-bottom: env( safe-area-inset-bottom); /* 兼容 iOS >= 11.2 */
	}
</style>